//
//  YYSPlayVideoController.m
//  FanLaiWu
//
//  Created by gonglei on 17/3/19.
//  Copyright © 2017年 yys. All rights reserved.
//

#import "YYSPlayVideoController.h"
#import "AGPlayerView.h"
#import "AppDelegate.h"
#import "YYSVideoJianjieCell.h"
#import "YYSGuessYourlikeCell.h"
#import "YYSDetailNewsVideoController.h"
#import "YYSVideoModel.h"
@interface YYSPlayVideoController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottonView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topPlayview;
@property (weak, nonatomic) IBOutlet UIView *botomView;
@property (nonatomic , assign) CGFloat cellHeight;
@property (nonatomic , strong) YYSVideoModel *videoModel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@end

@implementation YYSPlayVideoController
static NSString *ID = @"YYSVideoJianjieCell";
static NSString *ID2 = @"YYSGuessYourlikeCell";
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.fd_interactivePopDisabled = YES;
    
    
//    NSString *str = [[NSBundle mainBundle] pathForResource:@"e0200a6we70.p202.1[1].mp4" ofType:nil];
//    
//    NSURL * videoURL = [NSURL fileURLWithPath:str];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:ID bundle:nil] forCellReuseIdentifier:ID];
    [self.tableView registerNib:[UINib nibWithNibName:ID2 bundle:nil] forCellReuseIdentifier:ID2];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zhankai:) name:@"zhankai" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shouqi:) name:@"shouqi" object:nil];
    _cellHeight = 60;
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"id"] = self.ID;
    dict[@"token"] = TOKEN;
    //    dict[@"password"] = _passwordText.text;
    [NSObject POST:DETAILVIDEO__URL parameters:dict progress:^(NSProgress *downloadProgress) {
        
    } completionHandler:^(id responseObj, NSError *error) {
        NSLog(@"%@",responseObj);
        
        if ([responseObj[@"errno"] integerValue] == 0) {
            
            
            self.videoModel = [YYSVideoModel parseJSON:responseObj[@"result"]];
            self.player.titleLabel.text = self.videoModel.title;
            self.nameLabel.text = self.videoModel.title;
            [self.player updatePlayerWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASE_URL_TEST,self.videoModel.path]]];
            NSLog(@"%@",[NSString stringWithFormat:@"%@%@",BASE_URL_TEST,self.videoModel.path]);
            [self.tableView reloadData];
            
        } else {
            [SVProgressHUD showErrorWithStatus:responseObj[@"errmsg"]];
        }
    }];
    
}
- (void)zhankai:(NSNotificationCenter *)note
{
    CGSize _textLabelSize    = [self.videoModel.desc boundingRectWithSize:CGSizeMake(YYSScreenW-20, 100000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:15]} context:nil].size;
    _cellHeight = 50 + _textLabelSize.height;
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.tableView reloadData];
    }];
}
- (void)shouqi:(NSNotificationCenter *)note
{
    _cellHeight = 60;
    [self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (IBAction)clickshare:(UIButton *)sender {
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        
        //创建网页内容对象
        NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"欢迎使用【友盟+】社会化组件U-Share" descr:@"欢迎使用【友盟+】社会化组件U-Share，SDK包最小，集成成本最低，助力您的产品开发、运营与推广！" thumImage:thumbURL];
        //设置网页地址
        shareObject.webpageUrl = @"http://mobile.umeng.com/social";
        
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                UMSocialLogInfo(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    UMSocialLogInfo(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                    
                }else{
                    UMSocialLogInfo(@"response data is %@",data);
                }
            }
            
        }];
    }];
}
- (IBAction)clickXiaZai:(UIButton *)sender {
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        YYSVideoJianjieCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        cell.jianjieLabel.text = self.videoModel.desc;
        return cell;
    } else {
        YYSGuessYourlikeCell *cell = [tableView dequeueReusableCellWithIdentifier:ID2];
        return cell;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
//        return view;
    } else if (section == 1 || section == 2) {
        UIView *view = [UIView new];
        view.frame = CGRectMake(0, 0, YYSScreenW, 50);
        
        UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading"]];
        imageV.frame = CGRectMake(10, 20, 20, 20);
        [view addSubview:imageV];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 100, 20)];
        if (section == 1) {
            label.text = @"自制影片";
            view.tag = 1;
        } else if (section == 2){
            view.tag = 2;
            label.text = @"猜你喜欢";
        }
        label.textColor = YYSLabelTextColor;
        label.font = [UIFont systemFontOfSize:15];
        [view addSubview:label];
        
        UIImageView *imageV2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navright"]];
        imageV2.frame = CGRectMake(YYSScreenW - 40, 20, 20, 20);
        [view addSubview:imageV2];
        
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(YYSScreenW - 160, 22, 120, 18)];
        label2.text = @"更多精彩";
        
        
        label2.textColor = YYSLabelTextColor;
        label2.userInteractionEnabled = YES;
        label2.textAlignment = NSTextAlignmentRight;
        label2.font = [UIFont systemFontOfSize:15];
        [view addSubview:label2];
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, YYSScreenW, 10)];
        bottomView.backgroundColor = YYSRGBColor(235, 235, 235);
        [view addSubview:bottomView];
        [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickMore:)]];
        return view;
    } else {
        return nil;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else {
        return 40;
    }
}
- (void)clickMore:(UITapGestureRecognizer *)tap
{
    if (tap.view.tag == 1) {
        YYSDetailNewsVideoController *news = [[YYSDetailNewsVideoController alloc] init];
        news.title = @"自制影片";
        [self.navigationController pushViewController:news animated:YES];
    } else if (tap.view.tag == 2) {
        YYSDetailNewsVideoController *news = [[YYSDetailNewsVideoController alloc] init];
        news.title = @"猜你喜欢";
        [self.navigationController pushViewController:news animated:YES];
    }
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    
    //让头部视图随着滚动消失
    if (scrollView == self.tableView)
    {
        CGFloat sectionHeaderHeight = 220;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return _cellHeight;
    }
    return 330;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = 1;
    self.navigationController.navigationBar.hidden = YES;
}
-(void)dealloc
{
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = 0;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.player pause];
    [self.player updatePlayerWithURL:nil];
    self.player = nil;
}

// iOS 9.0 之后set方法弃用，需要在 controller 中实现
// 新方法 需要将View controller-based status bar appearance设置为YES,才会有效果,
// 1. 设置样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent; // 白色的
}
// 2. 横屏时显示 statusBar
- (BOOL)prefersStatusBarHidden {
//    NSLog(@"%d",self.player.isLandscape);
    if ([RotationScreen isOrientationLandscape] == YES) {
        
//        self.topPlayview.constant = 0;
//        self.bottonView.constant = 100;
        self.botomView.hidden = YES;
    } else {
        self.botomView.hidden = NO;
//        self.topPlayview.constant = -14;
//        self.bottonView.constant = 0;
    }
    return ![RotationScreen isOrientationLandscape];
    
//    return self.player.isLandscape; // 显示
}

// 3. 设置隐藏动画
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
